import { Context } from "egg";
import { verify } from 'jsonwebtoken'
export default (options) => {
  //获取token
  function getTokenValue(ctx: Context) {
    const { authorization } = ctx.header;
    if (!authorization || !ctx.helper) {
      return false;
    }
    if (
      authorization.trim().split(" ")[0] !== "Bearer" ||
      authorization.trim().split(" ").length === 2
    ) {
      return authorization.trim().split(" ")[1];
    } else {
      return false;
    }
  }
  return async (ctx: Context, next: () => Promise<any>) => {
    //获取header中的token
    const token = getTokenValue(ctx);
    if (!token) {
        return ctx.helper.error({ctx , errorType: 'UserLoginValidateError'})
    }
    if (!options.secret) {
        throw new Error("secret is required");
    }
    try {
        const decoded = verify(token, options.secret);
        ctx.state = decoded
        await next();
    } catch (error) {
        return ctx.helper.error({ctx , errorType: 'UserLoginValidateError'})
    }
  };
};
